package com.esdk.sql;

import com.esdk.esdk;
import com.esdk.sql.orm.IRow;
import com.esdk.sql.orm.ParentRow;
import com.esdk.utils.CharAppender;

import java.util.List;

public class PostgresDialect extends MysqlDialect{
  public PostgresDialect(){
    super(ConnMetaData.DatabaseProductName_PostgreSQL,null,null);
  }

  @Override
  public StringBuilder parseBatchReplace(String tableName,List<IRow> prs,boolean ignoreRowChanged){
    StringBuilder sb=super.parseBatchReplace(tableName,prs,ignoreRowChanged);
    sb.replace(0,"Replace Into".length(),"Insert Into");
    String pkname="";
    String[] excludes=null;
    if(prs.isEmpty()==false){
      Object first=(IRow)prs.getFirst();
      if(first instanceof ParentRow<?>){
        pkname=((ParentRow<?>)first).getPrimaryKeyName();
      }else if(first instanceof IRow<?>){
        pkname=((IRow<?>)first).getColumns()[0];
      }
      excludes=esdk.array.remove(((IRow<?>)first).getColumns(),pkname);
      CharAppender setCols=new CharAppender(',');
      for(String item: excludes){
        setCols.append(item+"=excluded."+item);
      }
      sb.append("ON CONFLICT("+pkname+") DO UPDATE SET ").append(setCols);
    }
    return sb;
  }
}
